<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    // 鼠标拖拽元素移动
    // 1. 鼠标按下 => 选中元素,元素可以移动(记录按下的位置)
    // 2. 鼠标移动 => 盒子跟随鼠标相对于按下的位置移动
    // 3. 鼠标松开 => 盒子不在跟随鼠标移动


    var box = document.getElementsByClassName("box")[0];
    var posX = null;
    var posY = null;

    box.addEventListener("mousedown", mouseHandler);

    // 鼠标按下 移动 松开 都触发同一个函数 => 对应事件类型区分 => 执行不同的内容
    function mouseHandler(e) {
        var e = e || window.event;
        if (e.type == "mousedown") {
            posX = e.offsetX;
            posY = e.offsetY;
            console.log(posX, posY);

            document.addEventListener("mousemove", mouseHandler);
            document.addEventListener("mouseup", mouseHandler);
        } else if (e.type == "mousemove") {
            var e = e || window.event;
            var x = e.pageX - posX;
            var y = e.pageY - posY;

            box.style.left = x + "px";
            box.style.top = y + "px";
        } else if (e.type == "mouseup") {
            document.removeEventListener("mousemove", mouseHandler);
            document.removeEventListener("mouseup", mouseHandler);
        }
    }






</script>

</html>